import { Reducer, Effect, Subscription } from 'umi';
import { getRemoteList, editUser, delUser, addUser, } from './service'
import { message } from 'antd';
import { UserObj } from './data.d';

export interface UserState {
    data: UserObj[];
    meta: {
        total: number,
        per_page: number,
        page: number
    };
}

interface UserModelType {
    namespace: 'users';
    state: UserState;
    reducers: {
        getList: Reducer<UserState>,
    };
    effects: {
        getRemote: Effect,
        edit: Effect,
        delete: Effect,
        add: Effect,
    };
    subscriptions: {
        setup: Subscription,
    };
}

const UserModel: UserModelType = {
    namespace: 'users',
    state: {
        data: [],
        meta: {
            total: 0,
            per_page: 5,
            page: 1
        },
    },
    reducers: {
        getList(state, { payload }) {
            return payload;
        },
    },
    effects: {
        *getRemote(action, { put, call }) {  //action = type + payload
            const data = yield call(getRemoteList);
            if (data) {
                yield put({
                    type: 'getList',
                    payload: data, //已经是对象不用包装
                });
            }
        },
        *edit({ payload: { id, values } }, { put, call }) {
            const data = yield call(editUser, { id, values });
            if (data) {
                yield put({
                    type: 'getRemote',
                });
                message.success('编辑成功');
            } else {
                message.error('编辑出错');
            }
        },
        *delete({ payload: { id } }, { put, call }) {
            const data = yield call(delUser, { id });
            if (data) {
                yield put({
                    type: 'getRemote',
                });
                message.success('删除成功');
            } else {
                message.error('删除失败');
            }
        },
        *add({ payload: { values } }, { put, call }) {
            const data = yield call(addUser, { values });
            if (data) {
                yield put({
                    type: 'getRemote',
                });
                message.success('添加成功');
            } else {
                message.error('添加失败');
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen((location, action) => {
                if (location.pathname === '/users') {
                    dispatch({
                        type: 'getRemote',
                    });
                }
            })
        }
    },
};

export default UserModel;